/**
 * @file appShell/common module
 * @author lavas
 */

const SET_PAGE_SWITCHING = 'SET_PAGE_SWITCHING',
      SET_TAB = 'SET_TAB',
      SET_USER_INFO = 'SET_USER_INFO',
      LOGOUT = 'LOGOUT',
      INIT_USER_INFO = 'INIT_USER_INFO'

export {
    SET_PAGE_SWITCHING,
    SET_TAB,
    SET_USER_INFO,
    LOGOUT,
    INIT_USER_INFO
}

export const state = () => {
    return {
        /**
         * 多个页面是否处于切换中
         *
         * @type {boolean}
         */
        isPageSwitching: false,

        /**
         * 当前 tab
         */
        currentTab: 'all',
        
        /**
         * 当前用户信息
         */
        userInfo: {}
    };
};

export const mutations = {
    [SET_PAGE_SWITCHING](state, isPageSwitching) {
        state.isPageSwitching = isPageSwitching;
    },
    [SET_TAB](state, tab) {
        state.currentTab = tab
    },
    [SET_USER_INFO](state, info) {
        if (info) {
            state.userInfo = Object.assign({}, info.userInfo, {
                accessToken: info.accessToken
            })
            localStorage.setItem('user-info', JSON.stringify(state.userInfo))
        }
    },
    [LOGOUT](state) {
        state.userInfo = {}
        localStorage.removeItem('user-info')
    },
    [INIT_USER_INFO](state) {
        let userInfo = localStorage.getItem('user-info')
        if (userInfo) {
            state.userInfo = JSON.parse(userInfo)
        }
    }
};

export const actions = {

    /**
     * 设置页面是否处于切换中
     *
     * @param {Function} commit commit
     * @param {boolean} isPageSwitching isPageSwitching
     */
    setPageSwitching({commit}, isPageSwitching) {
        commit(SET_PAGE_SWITCHING, isPageSwitching);
    }
};
